<template>
   <!--面包屑-->
<div style="margin-bottom: 30px">
 <el-breadcrumb separator="/">
   <el-breadcrumb-item :to="{ path: '/Main' }">首页</el-breadcrumb-item>
   <el-breadcrumb-item>
         <router-link to="/ListMaintenanceRecord">保养记录</router-link>
   </el-breadcrumb-item>
   <el-breadcrumb-item>保养记录显示</el-breadcrumb-item>
 </el-breadcrumb></div>
    <!-- 查询 -->
     <el-form :inline="true" :model="forms" class="demo-form-inline">
            <el-form-item label="保养负责人:">
      <el-input v-model="forms.MaintenanceHead" placeholder="请输入保养负责人" clearable style="width: 150px;"/>
    </el-form-item>
    <el-form-item label="当前保养日期:">
      <el-date-picker
             v-model="forms.CurrentMileageDate"
            type="date"
           placeholder="请输入当前保养日期"
            value-format="YYYY-MM-DD"
       clearable style="width: 180px;"
          />
   
    </el-form-item>
           <el-form-item label="车牌号:">
      <el-input v-model="forms.LicensePlateNumber" placeholder="请输入车牌号" clearable style="width: 150px;"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getListMaintenancesRecord">查询</el-button>
        <el-button type="primary" @click="reset()" >重置</el-button>
    </el-form-item>
  </el-form> 
  <!-- 显示列表 -->
       <el-button type="primary" @click="CreateMaintenances">新增</el-button>
           <el-button type="danger" @click="getDelAllMaintenancesRecord">删除</el-button>
            <el-button type="success" @click="getExport" >导出</el-button>
     <el-table :data="ListMaintenancesRecord" border style="width: 100%" ref="multipleTableRef"  @selection-change="handleSelectionChange">
       <el-table-column type="selection"  width="55" />
        <el-table-column prop="maintenanceTitle" label="保养标题" align="center" />
          <el-table-column prop="licensePlateNumber" label="车牌号" align="center" />
             <el-table-column prop="maintenancePrice" label="保养金额" align="center" />
               <el-table-column prop="maintenanceHead" label="保养负责人" align="center" />
                   <el-table-column prop="maintenanceProject" label="保养项目" align="center" />
                   <el-table-column prop="currentMileageDate" label="保养日期" align="center" >
                     <template v-slot="scope">
<span>{{ scope.row.currentMileageDate.replace("T"," ").substring(0,10)}}</span>
    </template>
                   </el-table-column>
                   <el-table-column prop="maintenanceRemark" label="备注" align="center" >
                    <template v-slot="scope">
<span v-if="scope.row.maintenanceRemark==''">-</span>
    </template>
                   </el-table-column>
    
 <el-table-column prop="createdDate" label="创建时间" align="center" >
                 <template v-slot="scope">
<span>{{ scope.row.createdDate.replace("T"," ").substring(0,19)}}</span>
    </template>
            </el-table-column>
                
             <el-table-column prop="date" label="操作" align="center">
  <template v-slot="scope">
    <!-- 编辑操作 -->
    <div class="table-operation">
      <el-icon class="operation-icon"><EditPen /></el-icon>
      <span class="operation-text" @click="edit(scope.row.maintenanceId)">编辑</span>
    </div>
 
    <!-- 删除操作 -->
    <div class="table-operation" style="margin-top: 8px;">
      <el-icon class="operation-icon"><CloseBold /></el-icon>
      <span class="operation-text" @click="del(scope.row.maintenanceId)">删除</span>
    </div>
 
    <!-- 查看操作 -->
    <div class="table-operation" style="margin-top: 8px;">
      <el-icon class="operation-icon"><CircleCheck /></el-icon>
      <span class="operation-text" @click="ed(scope.row.maintenanceId)">查看</span>
    </div>
  </template>
  
</el-table-column>
            
  </el-table>
  <!-- 分页 -->
  <div class="demo-pagination-block">

    <el-pagination
      v-model:current-page="page.PageIndex"
      v-model:page-size="page.PageSize"
      :page-sizes="[3, 6, 9, 11]"
     
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
    <!-- 查看保养单位信息 -->
   <div>
    <el-dialog
    v-model="dialogVisible1"
    title="保养信息"
    width="800"
  >
<el-form ref="ruleFormRef" style="max-width: 500px" :model="formm"  label-width="auto" 
        class="demo-ruleForm"  status-icon>

      <el-form-item label="保养标题：" prop="maintenanceTitle">
        <el-input v-model="formm.maintenanceTitle" placeholder="请输入保养标题" />
      </el-form-item>

      <el-form-item label="车牌号：" prop="licensePlateNumber">
       <el-select v-model="formm.licensePlateNumber" placeholder="请选择车牌号">
        <el-option v-for="item in PlateNumber" :label="item.plateNumber" :value="item.plateNumber" />

      </el-select>
      </el-form-item>


      <el-form-item label="保养金额：" prop="maintenancePrice">
        <el-input v-model="formm.maintenancePrice" placeholder="请输入保养金额" />
      </el-form-item>
      <el-form-item label="保养负责人:" prop="maintenanceHead">
        <el-input v-model="formm.maintenanceHead" placeholder="请输入保养负责人" />
      </el-form-item>
   <el-form-item label="当前里程数:" prop="currentMileage">
        <el-input v-model="formm.currentMileage" placeholder="请输入当前里程数" />
      </el-form-item>
        <el-form-item label="上次保养日期:" prop="lastMaintenanceDate">
              <el-date-picker
             v-model="formm.lastMaintenanceDate"
            type="date"
           value-format="YYYY-MM-DD"
           placeholder="请输入上次保养日期"
            style="width: 100%"
          />
 
      </el-form-item>
          <el-form-item label="上次保养里程数:" prop="lastMileage">
        <el-input v-model="formm.lastMileage" placeholder="请输入上次保养里程数" />
      </el-form-item>
            <el-form-item label="当前保养日期:" prop="currentMileageDate">
                 <el-date-picker
             v-model="formm.currentMileageDate"
            type="date"
           value-format="YYYY-MM-DD"
           placeholder="请输入当前保养日期"
            style="width: 100%"
          />
   
      </el-form-item>
            <el-form-item label="保养项目:" prop="maintenanceProject">
        <el-input v-model="formm.maintenanceProject" type="textarea" />
      </el-form-item>
      <el-form-item label="备注:" prop="maintenanceRemark">
        <el-input v-model="formm.maintenanceRemark" type="textarea" />
      </el-form-item>

</el-form>
      
    <template #footer>
      <div class="dialog-footer">
       
        <el-button type="primary" @click="dialogVisible1 = false">
          关闭
        </el-button> 
      </div>
    </template>
  </el-dialog>
   </div>
</template>
<script setup lang="ts">
//显示车牌号
const PlateNumber:any=ref([])
const showLicensePlateNumber = async () => {
    axios.get("/bread/api/Vehicles/GetVehicleShowPlateNumber").then((res) => {
        PlateNumber.value = res.data.data
    })
}
//查看信息
const dialogVisible1 = ref(false)
const formm= reactive({
   "maintenanceId": "",
  "companyID": "",
  "user_Id": "",
  "maintenanceTitle": "",
  "licensePlateNumber": "",
  "maintenancePrice": "",
  "maintenanceHead": "",
  "currentMileage": "",
  "lastMaintenanceDate": "",
  "lastMileage": "",
  "currentMileageDate": "",
  "maintenanceProject": "",
  "maintenanceRemark": "",
  "createdBy": "",
  "createdDate": "",
  "updatedBy": "",
  "updatedDate": "",
  "deletedBy": "",
  "deletedDate": "",
  "isDeleted": ""
})
const ed = (id:number) => {
    axios.get("/carwrite/api/MaintenanceRecord/MaintenanceRecordGetBy?MaintenanceId=" + id).then(ter => {
      formm.maintenanceId = ter.data.data.maintenanceId
      formm.companyID = ter.data.data.companyID
      formm.user_Id = ter.data.data.user_Id
      formm.maintenanceTitle = ter.data.data.maintenanceTitle
      formm.licensePlateNumber = ter.data.data.licensePlateNumber
      formm.maintenancePrice = ter.data.data.maintenancePrice
      formm.maintenanceHead = ter.data.data.maintenanceHead
      formm.currentMileage = ter.data.data.currentMileage
      formm.lastMaintenanceDate = ter.data.data.lastMaintenanceDate
      formm.lastMileage = ter.data.data.lastMileage
      formm.currentMileageDate = ter.data.data.currentMileageDate
      formm.maintenanceProject = ter.data.data.maintenanceProject
      formm.maintenanceRemark = ter.data.data.maintenanceRemark
      formm.createdBy = ter.data.data.createdBy
      formm.createdDate = ter.data.data.createdDate
      formm.updatedBy = ter.data.data.updatedBy
      formm.updatedDate = ter.data.data.updatedDate
      formm.deletedBy = ter.data.data.deletedBy
      formm.deletedDate = ter.data.data.deletedDate
      formm.isDeleted = ter.data.data.isDeleted
    })
   dialogVisible1.value = true
}
//分页
const handleSizeChange = (val: number) => {
    page.PageSize = val
  getListMaintenancesRecord()
}
const handleCurrentChange = (val: number) => {
    page.PageIndex = val  
  getListMaintenancesRecord()
}
//图标
import {
  Check,
  Delete,
  Edit,
  Message,
  Search,
    Star,
    CloseBold,
    EditPen,
  CircleCheck
} from '@element-plus/icons-vue'
//多选
const multipleSelection = ref([])
const multipleSelections = ref([])//整条数据
const handleSelectionChange = (val: any) => {
  multipleSelection.value = (val.map(d => d.maintenanceId))
        multipleSelections.value = val
   console.log(multipleSelection.value) //多选的id
  
}
//根据菜单id查询按钮功能权限
const form:any=reactive({
  buttonArray:[]
})
const getRoleMenuFun=()=>{
  axios.get('http://47.96.109.219:5202/api/RoleMenuFun/RoleMenuFunId', {
    params: {
      menuId:route.query.id
    }
  }).then(res=>{
    console.log(res);
    form.buttonArray=res.data.data
  }).catch(err=>{
    console.log(err);
    
  })    
}
//组件
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
const router = useRouter()
const route = useRoute()

//变量
const forms=reactive({
    MaintenanceHead: "",
  CurrentMileageDate: "",
    LicensePlateNumber:""
})
//分页
const page=reactive({
    PageIndex: 1,
    PageSize: 3,
    pageCount: 0,
    totalCount:0
})
//方法
//显示保养方法
const ListMaintenancesRecord: any = ref([])
const getListMaintenancesRecord = () => {
    axios.get("/carread/api/MaintenanceRecords/GetMaintenancesRecordAll", {
        params: {
            MaintenanceHead: forms.MaintenanceHead,
        CurrentMileageDate: forms.CurrentMileageDate,
                 LicensePlateNumber: forms.LicensePlateNumber,
            PageIndex: page.PageIndex,
            PageSize:page.PageSize,
        }
    }).then(ter => {
        ListMaintenancesRecord.value = ter.data.data.list
     console.log(ter.data)
        page.pageCount = ter.data.data.pageCount
        page.totalCount = ter.data.data.totalCount
      
    
    }).catch(err => {
        console.log(err);
    })
}
//重置查询条件
const reset = () => {
     forms.MaintenanceHead="",
    forms.CurrentMileageDate="",
    forms.LicensePlateNumber="",

    getListMaintenancesRecord()
}
//导出
import * as XLSX from 'xlsx';// 导出Excel
const getExport = () => {
  // let url = '/bread/api/CargoOwners/GetExcelName?CargoOwnerName='+forms.CargoOwnerName+'&CargoOwnerPhone='+forms.CargoOwnerPhone+'&DriverLicenseDate='+forms.DriverLicenseDate+'&PageIndex='+page.PageIndex+'&PageSize='+page.PageSize
  // window.location.href = url;
    ElMessageBox.confirm("是否确认导出当前选择的数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
    .then((response) => {
        //  this.selectdata 是复选框的 数据列表
        if (multipleSelections.value.length <= 0) {
            ElMessage.warning('请选择数据！');
            return;
        }
        let tableData = [
            ['序号','保养标题','车牌号', '保养金额', '保养负责人',"保养项目","保养日期","备注","创建时间"]//导出表头
        ] // 表格表头
        multipleSelections.value.forEach((item, index) => {
            let rowData= []
            //导出内容的字段
            rowData = [
                index + 1, 
                item.maintenanceTitle,
                item.licensePlateNumber,
              item.maintenancePrice,
                  item.maintenanceHead,
                item.maintenanceProject,
              item.currentMileageDate,
              item.maintenanceRemark,
              item.createdDate,
             

            ]
            tableData.push(rowData)
        })
        let workSheet = XLSX.utils.aoa_to_sheet(tableData);
        let bookNew = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(bookNew, workSheet, '作品名称') // 工作簿名称
        let name = '保养记录表' + timeFormat() + '.xlsx'
        XLSX.writeFile(bookNew, name) // 保存的文件名
    })
}
const timeFormat=()=> {
        let time = new Date();
        let year = time.getFullYear();
        let month = time.getMonth() + 1;
        let date = time.getDate();
        let hours = time.getHours();
        let minutes = time.getMinutes();
        let seconds = time.getSeconds();
        return year + '-' + addZero(month) + '-' + addZero(date) + ' ' + addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds);
}
const addZero=(num:any)=> {
    return num < 10 ? '0' + num : num
}
//删除（单删）
import { ElMessage, ElMessageBox } from 'element-plus'
const del = (id:number) => {
     ElMessageBox.confirm(
    '确定要删除吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
        axios.post("/carwrite/api/MaintenanceRecord/DeleteMaintenanceRecord?MaintenanceId="+id).then(ter => {
            if (ter.data.code>0) {
                ElMessage.success('删除成功')
            getListMaintenancesRecord()
            }
            else {
            ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
    
    })
}
//新增保养信息跳转
const CreateMaintenances = () => {
    router.push("/CreateMaintenanceRecord")
}
//删除（多删）
const getDelAllMaintenancesRecord = () => {
    if (multipleSelection.value.length == 0) { 
        ElMessage.error('请选择要删除的保养记录信息')
        return
    }
      ElMessageBox.confirm(
    '确定要删除吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
          .then(() => {

              axios.post("/carwrite/api/MaintenanceRecord/DeleteAllMaintenanceRecord", {
            ids:multipleSelection.value
        }).then(ter => {
            if (ter.data.code>0) {
                ElMessage.success('删除成功')
                 getListMaintenancesRecord()
            }
            else {
            ElMessage.error('删除失败')
        }
      })
    })
    .catch(() => {
    
    })
}
//修改保养信息
const edit = (id:number) => {
    router.push({
        path: "/UpdateMaintenanceRecord",
        query: {
            id:id
        }
    })
}

//钩子函数
onMounted(async() => {
  getListMaintenancesRecord()
  showLicensePlateNumber()
    getRoleMenuFun()
})
</script>
<style scoped>
.table-operation {
  display: flex;
  align-items: center;
}
 
.operation-icon {
  color: blue;
  margin-right: 8px; /* 图标和文本之间的间距 */
}
 
.operation-text {
  color: blue;
  cursor: pointer; /* 鼠标悬停时显示为可点击 */
}
</style>
